package com.candy.candyproduct.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.candy.candycommon.exception.BusinessException;
import com.candy.candycommon.manager.MultiThreadTransaction;
import com.candy.candyproduct.bean.Product;
import com.candy.candyproduct.mapper.ProductMapper;
import com.candy.candyproduct.service.ProductService;
import com.candy.candyproductservice.dto.ProductDTO;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/3/28 14:45
 * @Description 描述
 */
@Slf4j
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    PlatformTransactionManager transactionManager;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @Transactional(rollbackFor = Exception.class)
    public boolean subProduct(ProductDTO productDTO) {
        Integer integer = baseMapper.subProduct(productDTO);
//        int i = 1 / 0;
        if (integer == 0) {
            throw new BusinessException("库存不够");
        }
        return integer > 0;
    }

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public boolean batchMultiThread(List<Product> list) {
        /*
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(20);
        // 创建多线程事务管理器，传入事务管理器，指定超时时间为3秒
        MultiThreadingTransactionManager multiThreadingTransactionManage = new MultiThreadingTransactionManager(transactionManager, 3, TimeUnit.SECONDS);
        List<Runnable> runnableList = new ArrayList<>();
        // 模拟任务出现异常
        // runnableList.add(() -> {
        //     int a = 10 / 0;
        // });
        list.forEach((x) -> {
            runnableList.add(new Runnable() {
                @Override
                public void run() {
                    System.out.println("当前线程：" + Thread.currentThread().getName() + "插入数据：" + x);
                    baseMapper.insert(x);
                    // 模拟异常
                    if (x.getProNum() == 1) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        int ex = 1 / 0;
                    }
                }
            });
        });
        // 执行
        return multiThreadingTransactionManage.execute(runnableList, executor);*/
        MultiThreadTransaction threadTransaction = new MultiThreadTransaction(threadPoolTaskExecutor, transactionManager);
        threadTransaction.batchSchedule(list, list1 -> {
            this.saveBatch(list1);
        });
        return true;
    }

    //    @PostConstruct
    public void test() {
        ProductDTO productDTO = new ProductDTO();
        productDTO.setId(1l);
        productDTO.setSubNum(1);
        boolean result = subProduct(productDTO);
        log.info("result:{}", result);
    }

    //    @PostConstruct
    public void testAdd() {
        Product product = new Product();
        product.setProNum(100);
        product.setProName("testAdd");
        baseMapper.insert(product);
    }

}
